import { LocalizedLabel } from "../Language/LocalizedLabel";

const { ccclass, property } = cc._decorator;

/**
 * 倒计时按钮
 */
@ccclass
export class ButtonWithCountdown extends cc.Component {
    @property(cc.Sprite)
    sp: cc.Sprite = null
    @property(LocalizedLabel)
    lab: LocalizedLabel = null
    @property(cc.Integer)
    cdTime: number = 60

    btn: cc.Button;
    private _textKey: string;
    private _cdTime: number;

    onLoad() {
        cc.log(`${cc.js.getClassName(this)} onLoad`)

        this.btn = this.node.getComponent(cc.Button)
        this.node.on(cc.Node.EventType.TOUCH_END, (event: cc.Event) => {
            cc.log(`${cc.js.getClassName(this)} onBtn`)

            if (this.btn.interactable) {
                this.btn.interactable = false
                this.sp.setState(cc.Sprite.State.GRAY)
                this._textKey = this.lab.textKey
                this._cdTime = this.cdTime
                this.lab.textKey = this._cdTime.toString()
            }
        })
    }

    start() {
        cc.log(`${cc.js.getClassName(this)} start`)

    }

    update(dt: number) {
        if (this._cdTime >= 0) {
            let time = Math.ceil(this._cdTime)
            this.lab.textKey = time.toString()
            this._cdTime -= dt
            if (this._cdTime < 0) {
                this.btn.interactable = true
                this.sp.setState(cc.Sprite.State.NORMAL)
                this.lab.textKey = this._textKey
            }
        }
    }

    // ====================================================================================
    // ===================================== 内部接口 ======================================
    // ====================================================================================

    // ====================================================================================
    // ===================================== 外部接口 ======================================
    // ====================================================================================
}